using System.Collections.Generic;
using Verse;
using Verse.AI;

namespace RimWorld;

public class WorkGiver_TakeToBedToOperate : WorkGiver_TakeToBed
{
	public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForGroup(ThingRequestGroup.Pawn);

	public override PathEndMode PathEndMode => PathEndMode.OnCell;

	public override Danger MaxPathDanger(Pawn pawn)
	{
		return Danger.Deadly;
	}

	public override bool ShouldSkip(Pawn pawn, bool forced = false)
	{
		List<Pawn> allPawnsSpawned = pawn.Map.mapPawns.AllPawnsSpawned;
		for (int i = 0; i < allPawnsSpawned.Count; i++)
		{
			if (HealthAIUtility.ShouldHaveSurgeryDoneNow(allPawnsSpawned[i]))
			{
				return false;
			}
		}
		return true;
	}

	public override IEnumerable<Thing> PotentialWorkThingsGlobal(Pawn pawn)
	{
		return pawn.Map.mapPawns.SpawnedPawnsWhoShouldHaveSurgeryDoneNow;
	}

	public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false)
	{
		if (!(t is Pawn pawn2) || pawn2 == pawn || pawn2.InBed() || !pawn2.RaceProps.IsFlesh || !HealthAIUtility.ShouldHaveSurgeryDoneNow(pawn2) || !pawn.CanReserve(pawn2, 1, -1, null, forced) || (pawn2.InMentalState && pawn2.MentalStateDef.IsAggro))
		{
			return false;
		}
		if (!pawn2.Downed)
		{
			if (pawn2.IsColonist || pawn2.CurJobDef == JobDefOf.LayDown)
			{
				return false;
			}
			if (!pawn2.IsPrisonerOfColony && pawn2.Faction != Faction.OfPlayer)
			{
				return false;
			}
			if (pawn2.guest != null && pawn2.guest.Released)
			{
				return false;
			}
		}
		Building_Bed building_Bed = FindBed(pawn, pawn2);
		if (building_Bed != null && pawn2.CanReserve(building_Bed, building_Bed.SleepingSlotsCount))
		{
			return true;
		}
		return false;
	}

	public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false)
	{
		Pawn pawn2 = t as Pawn;
		Building_Bed building_Bed = FindBed(pawn, pawn2);
		Job job = JobMaker.MakeJob(JobDefOf.TakeToBedToOperate, pawn2, building_Bed);
		job.count = 1;
		return job;
	}
}
